<template>
    <div class="user-card">
        <div class="user-avatar" @click="goToUserDetail">
            <img :src="user.avatar || '/default-avatar.png'" alt="头像" />
        </div>

        <div class="user-info">
            <div class="user-main">
                <h3 class="username" @click="goToUserDetail">
                    {{ displayName }}
                </h3>
                <div class="user-meta">
                    <span v-if="user.position" class="position">
                        <el-icon>
                            <Briefcase />
                        </el-icon>
                        {{ user.position }}
                    </span>
                    <span v-if="user.city" class="city">
                        <el-icon>
                            <Location />
                        </el-icon>
                        {{ user.city }}
                    </span>
                </div>
                <p v-if="user.bio" class="bio">{{ user.bio }}</p>
            </div>

            <div class="user-actions">
                <el-button v-if="user.user_id !== currentUserId" :type="isFollowing ? 'default' : 'primary'"
                    size="small" :loading="followLoading" @click="isFollowing ? handleUnfollow() : handleFollow()">
                    {{ isFollowing ? '已关注' : '关注' }}
                </el-button>
                <el-button v-else size="small" disabled>
                    自己
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Briefcase, Location } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useFollowsStore } from '@/stores/follow'

const props = defineProps({
    user: {
        type: Object,
        required: true
    }
})

const router = useRouter()
const userStore = useUserStore()
const followsStore = useFollowsStore()

const followLoading = ref(false)
const isFollowing = ref(false)

const currentUserId = computed(() => userStore.getUserId())

const displayName = computed(() => {
    return props.user.nickname || props.user.email || '未知用户'
})

// 检查关注状态
const checkFollowStatus = async () => {
    if (props.user.user_id === currentUserId.value) return

    try {
        const result = await followsStore.fetchFollowingList(currentUserId.value, {
            page: 1,
            pageSize: 1000
        })

        if (result.code === 0) {
            const followingList = result.data.list || []
            const isUserFollowed = followingList.some(item =>
                item.follow_id === props.user.user_id ||
                item.user?.user_id === props.user.user_id
            )
            isFollowing.value = isUserFollowed
        }
    } catch (error) {
        console.error('检查关注状态失败:', error)
    }
}

// 关注用户
const handleFollow = async () => {
    if (followLoading.value) return

    try {
        followLoading.value = true
        await followsStore.followUserAction(String(props.user.user_id))
        isFollowing.value = true
        ElMessage.success('关注成功')

        // 触发统计更新事件
        window.dispatchEvent(new CustomEvent('followStatusChanged'))
    } catch (error) {
        ElMessage.error(error.message || '关注失败')
    } finally {
        followLoading.value = false
    }
}

// 取消关注
const handleUnfollow = async () => {
    if (followLoading.value) return

    try {
        followLoading.value = true
        await followsStore.unfollowUserAction(props.user.user_id)
        isFollowing.value = false
        ElMessage.success('取消关注成功')

        // 触发统计更新事件
        window.dispatchEvent(new CustomEvent('followStatusChanged'))
    } catch (error) {
        ElMessage.error(error.message || '取消关注失败')
    } finally {
        followLoading.value = false
    }
}

// 跳转到用户详情
const goToUserDetail = () => {
    router.push(`/user/${props.user.user_id}`)
}

onMounted(() => {
    checkFollowStatus()
})
</script>

<style scoped>
.user-card {
    display: flex;
    align-items: flex-start;
    padding: 16px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    margin-bottom: 12px;
}

.user-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.user-avatar {
    flex-shrink: 0;
    margin-right: 16px;
    cursor: pointer;
}

.user-avatar img {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #f0f0f0;
}

.user-info {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

.user-main {
    flex: 1;
}

.username {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
    cursor: pointer;
    transition: color 0.2s;
}

.username:hover {
    color: #1890ff;
}

.user-meta {
    display: flex;
    gap: 16px;
    margin-bottom: 8px;
    font-size: 12px;
    color: #666;
}

.user-meta span {
    display: flex;
    align-items: center;
    gap: 4px;
}

.bio {
    margin: 0;
    font-size: 14px;
    color: #666;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.user-actions {
    flex-shrink: 0;
    margin-left: 16px;
}
</style>